import 'package:baselib/utils/image_util.dart';
import 'package:baselib/utils/log_util.dart';
import 'package:baselib/utils/time_util.dart';
import 'package:baselib/widgets/comm_app_bar.dart';
import 'package:baselib/widgets/gradient_card_view.dart';
import 'package:baselib/widgets/inkwell_button.dart';
import 'package:baselib/widgets/refresh_util.dart';
import 'package:flutter/material.dart';
import 'package:framelib/utils/color_util.dart';
import 'package:framelib/utils/drawable_util.dart';
import 'package:framelib/utils/px_util.dart';
import 'package:framelib/utils/string_util.dart';
import 'package:framelib/widgets/chat_message_audio_item.dart';
import 'package:framelib/widgets/chat_message_image_item.dart';
import 'package:framelib/widgets/chat_message_video_item.dart';
import 'package:framelib/widgets/comm_widget_manager.dart';
import 'package:framelib/widgets/emoji_panel.dart';
import 'package:framelib/widgets/page_widget.dart';
import 'package:framelib/widgets/record_panel.dart';
import 'package:get/get.dart';
import 'package:module_business/module_chat/viewmodel/chat_view_model.dart';
import 'package:module_business/module_comm/model/user_params_model.dart';
import 'package:module_business/module_index/viewmodel/index_view_model.dart';
import 'package:nim_core/nim_core.dart';
/**
 * 主页
 */
class ChatPage extends GetWidget<ChatViewModel> {

  ChatPage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Get.put(ChatViewModel());
    return PageWidget.build(
        builder: (ChatViewModel model){
          return PageWidget.PageScaffoldWidget(
            isShowBg: true,
            appBar: CommAppBar(
              backgroundColor: ColorUtil.instance.color_transparent,
              titleStr: model.voicePersonNickName??'',
              titleTextStyle: TextStyle(
                  fontSize: PxUtil.instance.px_18,
                  color: ColorUtil.instance.color_white,
                  fontWeight: FontWeight.bold
              ),
              actions: [
                InkWellButton(
                  onPressed: ()=>model.showChatOper(),
                  child: Container(
                    padding: EdgeInsets.only(
                      left: PxUtil.instance.px_15,
                      right: PxUtil.instance.px_15,
                    ),
                    child: ImagesUtil.loadAssetImage(
                        DrawableUtil.instance.icon_chat_room_more,
                        width: PxUtil.instance.px_5,
                        fit: BoxFit.fitWidth
                    ),
                  ),
                ),
              ],
            ),
            floatingActionButton: Container(
              margin: EdgeInsets.only(
                bottom: PxUtil.instance.px_50
              ),
              child: InkWellButton(
                onPressed: ()=>model.openGiftsUi(),
                child: ImagesUtil.loadAssetImage(
                    DrawableUtil.instance.icon_chat_gifts,
                    width: PxUtil.instance.px_56
                ),
              ),
            ),
            bottomNavigationBar: AnimatedPadding(
              padding: MediaQuery.of(context).viewInsets,
              duration: Duration(milliseconds: 100),
              child: Container(
                width: PxUtil.instance.screenWidth,
                padding: EdgeInsets.only(
                  bottom: PxUtil.instance.px_10,
                  top: PxUtil.instance.px_10,
                ),
                color: ColorUtil.instance.color_37416d,
                // color: ColorUtil.instance.color_white,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      width: PxUtil.instance.screenWidth,
                      child: Row(
                        children: [
                          SizedBox(width: PxUtil.instance.px_15,),
                          Expanded(
                              child: Container(
                                height: PxUtil.instance.px_42,
                                alignment: Alignment.centerLeft,
                                decoration: BoxDecoration(
                                    color: ColorUtil.instance.color_495279,
                                    borderRadius:
                                    BorderRadius.circular(PxUtil.instance.px_21)),
                                child: Row(
                                  children: [
                                    Expanded(child: TextField(
                                      style: TextStyle(
                                          color: ColorUtil.instance.color_white
                                      ),
                                      enabled: true,
                                      textAlign: TextAlign.start,
                                      maxLength: 200,
                                      maxLines: 1,
                                      textInputAction: TextInputAction.done,
                                      keyboardType: TextInputType.text,
                                      autofocus: false,
                                      controller: model.commentController,
                                      scrollController: model.commentScrollController,
                                      // onChanged: (value)=>model.onCommentChanged(value),
                                      cursorColor: ColorUtil.instance.color_white,
                                      decoration: InputDecoration(
                                          contentPadding: EdgeInsets.only(
                                            left: PxUtil.instance.px_15,
                                            right: PxUtil.instance.px_15,
                                            bottom: PxUtil.instance.px_0,
                                          ),
                                          isDense: true,
                                          counterText: "",
                                          hintText: '${StringUtil.instance.Please_Input}...',
                                          hintStyle: TextStyle(
                                              color: ColorUtil.instance.color_half_white
                                          ),
                                          focusedBorder: UnderlineInputBorder(
                                              borderSide: BorderSide(
                                                  color: ColorUtil
                                                      .instance.color_transparent,
                                                  width: 1)),
                                          enabledBorder: UnderlineInputBorder(
                                              borderSide: BorderSide(
                                                  color: ColorUtil
                                                      .instance.color_transparent,
                                                  width: 1))),
                                    ),),
                                    Obx(() => InkWellButton(
                                      onPressed: ()=>model.emojiSelect(),
                                      child: Container(
                                        margin: EdgeInsets.only(
                                          left: PxUtil.instance.px_10,
                                          right: PxUtil.instance.px_10,
                                        ),
                                        child: ImagesUtil.loadAssetImage(
                                            DrawableUtil.instance.icon_chat_emoji,
                                            width: PxUtil.instance.px_24,
                                            color: (model.emojiSelected.value??false)?Colors.blue:Colors.white60
                                        ),
                                      ),
                                    ))
                                  ],
                                )
                              )),
                          InkWellButton(
                            onPressed: ()=>model.sendMsg(),
                            child: Container(
                              margin: EdgeInsets.only(
                                left: PxUtil.instance.px_15,
                                right: PxUtil.instance.px_15,
                              ),
                              child: GradientCardView(
                                elevation: PxUtil.instance.px_0,
                                gradient: LinearGradient(
                                    begin: Alignment.topCenter,
                                    end: Alignment.bottomCenter,
                                    colors: [
                                      ColorUtil.instance.color_7776FF,
                                      ColorUtil.instance.color_AD2CF1,
                                    ]
                                ),
                                padding: EdgeInsets.only(
                                  left: PxUtil.instance.px_22,
                                  right: PxUtil.instance.px_22,
                                  top: PxUtil.instance.px_13,
                                  bottom: PxUtil.instance.px_13,
                                ),
                                borderRadius: BorderRadius.circular(
                                    PxUtil.instance.px_26),
                                child: Text(
                                  StringUtil.instance.Send,
                                  style: TextStyle(
                                      color: ColorUtil.instance.color_white
                                  ),
                                ),
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                        top: PxUtil.instance.px_12,
                        bottom: PxUtil.instance.px_12,
                      ),
                      child: Row(
                        children: [
                          SizedBox(width: PxUtil.instance.px_15,),
                          Obx(() => InkWellButton(
                            onPressed: ()=>model.voiceSelect(),
                            child: Container(
                              child: ImagesUtil.loadAssetImage(
                                  DrawableUtil.instance.icon_chat_voice,
                                  width: PxUtil.instance.px_32,
                                  color: (model.voiceSelected.value??false)?Colors.blue:Colors.white60
                              ),
                            ),
                          )),
                          SizedBox(width: PxUtil.instance.px_26,),
                          Obx(() => InkWellButton(
                            onPressed: ()=>model.pictureSelect(),
                            child: ImagesUtil.loadAssetImage(
                                DrawableUtil.instance.icon_chat_select_img,
                                width: PxUtil.instance.px_32,
                                color: (model.pictureSelected.value??false)?Colors.blue:Colors.white60
                            ),
                          )),
                          SizedBox(width: PxUtil.instance.px_26,),
                          Obx(() => InkWellButton(
                            onPressed: ()=>model.videoSelect(),
                            child: ImagesUtil.loadAssetImage(
                                DrawableUtil.instance.icon_chat_select_video,
                                width: PxUtil.instance.px_32,
                                color: (model.videoSelected.value??false)?Colors.blue:Colors.white60
                            ),
                          ))
                        ],
                      ),
                    ),
                    Obx(() => AnimatedContainer(
                      duration: const Duration(milliseconds: 300),
                      height: model.isOpenButtonUi()?_getPanelHeight():PxUtil.instance.px_0,
                      child: _getPanel(model),
                    ))
                  ],
                ),
              ),
            ),
            body: RefreshUtil.init(
              model.refreshController,
                  ()=>model.onRefresh(pageCur: model?.page=1),
                  null,
              Obx(() => _buildListUi(model)),
              physics: ClampingScrollPhysics(),
              loadStatus: model?.loadStatus,
              enablePullDown: true,
              enablePullUp: false,
              isCanMoreData: false,
              reverse: true,
              onReFreshFunction:()=>model.onRefresh(pageCur: model?.page=1),
            ),
          );
        }
    );
  }
  double _getPanelHeight() {
    // if (_currentType == ActionConstants.record ||
    //     _currentType == ActionConstants.more ||
    //     _currentType == ActionConstants.emoji) {
    //   return 197;
    // }
    // return 0;
    return 197;
  }
  Widget _getPanel(ChatViewModel model) {
    if (model.voiceSelected.value??false) {
      return RecordPanel(
          onPressedDown: () =>(model.recording.value = true),
          onEnd: () =>(model.recording.value = false),
          onCancel: () =>(model.recording.value = false),
          audioMessageCallBack: (String filePath, int fileSize, int duration)=>model.sendAudioMessage(filePath,fileSize,duration)
      );
    }
    // if (_currentType == ActionConstants.more) {
    //   return MorePanel(
    //     moreActions: widget.chatUIConfig?.moreActions,
    //   );
    // }
    if (model.emojiSelected.value??false) {
      return EmojiPanel(
        onEmojiSelected: (emoji) {
          final text = model.commentController.text;
          final textFinal =  "$text$emoji";
          model.commentController.text = textFinal;
          model.commentController.selection=TextSelection.fromPosition(TextPosition(
              affinity: TextAffinity.downstream,
              offset: textFinal.length));
          // inputText = model.commentController.text;
          // Future.delayed(Duration(milliseconds: 20), () {
          //   model.commentScrollController
          //       .jumpTo(model.commentScrollController.position.maxScrollExtent);
          // });
        },
        onEmojiDelete: () {
          String originText = model.commentController.text;
          var text = originText.characters.skipLast(1);
          model.commentController.text = "$text";
          model.commentController.selection=TextSelection.fromPosition(TextPosition(
              affinity: TextAffinity.downstream,
              offset: model.commentController.text.length));
          // inputText = model.commentController.text;
        },
      );
    }
    return Container();
  }
  Widget _buildListUi(ChatViewModel model) {
    return ListView.builder(
        physics: NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        itemCount: model.msgDatas.value.length??0,
        itemBuilder: (BuildContext context,int index){
          NIMMessage msgDataItem = model.msgDatas.value[index];
          LogUtil.d('otherAccId--->${model.voicePersonYxAccid}');
          LogUtil.d('selfAccId--->${UserParamsModel.instance.yxAccid}');
          LogUtil.d('msgDataItem--->${msgDataItem?.toMap()}');
          if(msgDataItem?.fromAccount == UserParamsModel.instance.yxAccid){
            //自己
            return buildSelfMsgUi(model,msgDataItem);
          }else{
            //别人
            return buildOtherMsgUi(model,msgDataItem);
          };
        }
    );
  }

  Widget buildSelfMsgUi(ChatViewModel model, NIMMessage msgDataItem) {
    return Container(
      width: PxUtil.instance.screenWidth,
      margin: EdgeInsets.only(
        bottom: PxUtil.instance.px_30
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: PxUtil.instance.screenWidth/4,
          ),
          Expanded(child: Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              _buildChatItemUi(model,msgDataItem),
              SizedBox(height:  PxUtil.instance.px_5,),
              Text(
                '${TimeUtils.forMatTimeByMs(msgDataItem?.timestamp,format: 'yyyy-MM-dd HH:mm:ss')}',
                style: TextStyle(
                    fontSize: PxUtil.instance.px_8,
                    color: ColorUtil.instance.color_white
                ),
              )
            ],
          )),
          Container(
              margin: EdgeInsets.only(
                  left: PxUtil.instance.px_12,
                  right: PxUtil.instance.px_12
              ),
              child:
              CommWidgetManager.buildCicleImagWidget(
                UserParamsModel.instance.userEntity?.icon ?? '',
                placeholder:
                DrawableUtil.instance.icon_default_head,
                width: PxUtil.instance.px_32,
                height: PxUtil.instance.px_32,
                roundRadius: PxUtil.instance.px_16,
                backgroundColor: ColorUtil.instance.color_f2f2f2,
                padding: EdgeInsets.only(),
                margin: EdgeInsets.only(),
              )
          ),
        ],
      ),
    );
  }
  Widget buildOtherMsgUi(ChatViewModel model, NIMMessage msgDataItem) {
    return Container(
      width: PxUtil.instance.screenWidth*3/4,
      margin: EdgeInsets.only(
          bottom: PxUtil.instance.px_30
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
              margin: EdgeInsets.only(
                  left: PxUtil.instance.px_12,
                  right: PxUtil.instance.px_12
              ),
              child:
              InkWellButton(
                onPressed: ()=>model.toPersonHome(),
                child: CommWidgetManager.buildCicleImagWidget(
                  model.voicePersonIcon ?? '',
                  placeholder:
                  DrawableUtil.instance.icon_default_head,
                  width: PxUtil.instance.px_32,
                  height: PxUtil.instance.px_32,
                  roundRadius: PxUtil.instance.px_16,
                  backgroundColor: ColorUtil.instance.color_f2f2f2,
                  padding: EdgeInsets.only(),
                  margin: EdgeInsets.only(),
                ),
              )
          ),
          Expanded(child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildChatItemUi(model,msgDataItem),
              SizedBox(height:  PxUtil.instance.px_5,),
              Text(
                '${TimeUtils.forMatTimeByMs(msgDataItem?.timestamp,format: 'yyyy-MM-dd HH:mm:ss')}',
                style: TextStyle(
                    fontSize: PxUtil.instance.px_8,
                    color: ColorUtil.instance.color_white
                ),
              )
            ],
          )),
          SizedBox(
            width: PxUtil.instance.screenWidth/4,
          ),
        ],
      ),
    );
  }

  _buildChatItemUi(ChatViewModel model, NIMMessage msgDataItem) {
    switch (msgDataItem.messageType) {
      case NIMMessageType.text:
        return Container(
          padding: EdgeInsets.only(
            left: PxUtil.instance.px_15,
            right: PxUtil.instance.px_15,
            top: PxUtil.instance.px_10,
            bottom: PxUtil.instance.px_10,
          ),
          decoration: BoxDecoration(
              color: ColorUtil.instance.color_4b5e91,
              borderRadius: BorderRadius.circular(PxUtil.instance.px_20)
          ),
          child: Text(
            '${msgDataItem?.content??''}',
            style: TextStyle(
                color: ColorUtil.instance.color_white,
                fontSize: PxUtil.instance.px_14
            ),
          ),
        );
      case NIMMessageType.audio:
        return ChatMessageAudioItem(
          message: msgDataItem,
        );
      case NIMMessageType.image:
        return ChatMessageImageItem(
          message: msgDataItem,
        );
      case NIMMessageType.video:
        return ChatMessageVideoItem(
          message: msgDataItem,
        );
      // case NIMMessageType.notification:
      //   if (messageItemBuilder?.notifyMessageBuilder != null) {
      //     return messageItemBuilder!.notifyMessageBuilder!(message.nimMessage);
      //   }
      //   return ChatKitMessageNotificationItem(message: message.nimMessage);
      // case NIMMessageType.tip:
      //   if (messageItemBuilder?.tipsMessageBuilder != null) {
      //     return messageItemBuilder!.tipsMessageBuilder!(message.nimMessage);
      //   }
      //   return ChatKitMessageTipsItem(message: message.nimMessage);
      default:
        return Container(
          padding: EdgeInsets.only(
            left: PxUtil.instance.px_15,
            right: PxUtil.instance.px_15,
            top: PxUtil.instance.px_10,
            bottom: PxUtil.instance.px_10,
          ),
          decoration: BoxDecoration(
              color: ColorUtil.instance.color_4b5e91,
              borderRadius: BorderRadius.circular(PxUtil.instance.px_20)
          ),
          child: Text(
            '${msgDataItem?.content??''}',
            style: TextStyle(
                color: ColorUtil.instance.color_white,
                fontSize: PxUtil.instance.px_14
            ),
          ),
        );
    }
  }
}
